package com.example.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringExclude;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class myUtils {
    static public int pageSize = 5;

    static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();

    static String mod="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**
     * 返回长度为len的随机字符串
     * @param len
     * @return
     */
    public static String getString(int len){
        String res="";
        Random rand = new Random();
        while((len--)>0){
            res+=mod.charAt(rand.nextInt(mod.length()));
        }
        return res;
    }
    /**
     * 提取html中的文字
     *
     * @param html
     * @return
     */
    public static String htmlToText(String html) {
        if (StringUtils.isNotBlank(html)) {
            return html.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " ");
        }
        return "";
    }

    /**
     * Markdown转换为Html
     * @param markdown
     * @return     ok
     */
    public static String mdToHtml(String markdown) {
        if (StringUtils.isBlank(markdown)) {
            return "";
        }
        List<Extension> extensions = Arrays.asList(TablesExtension.create());
        Parser parser = Parser.builder().extensions(extensions).build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder()
                .attributeProviderFactory(context -> new LinkAttributeProvider())
                .extensions(extensions).build();
        String content = renderer.render(document);
        content = commons.emoji(content);
        return content;
    }

    /**
     * 替换HTML脚本
     *
     * @param value
     * @return
     */
    public static String cleanXSS(String value) {
        value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
        value = value.replaceAll("'", "&#39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        return value;
    }

    private static class LinkAttributeProvider implements AttributeProvider {
        @Override
        public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
            if (node instanceof Link) {
                attributes.put("target", "_blank");
            }
        }
    }
    /**
     * 将二进制转换为图片
     *
     * @param base64String
     * @return
     */
    public static BufferedImage base64StringToImage(String base64String) throws IOException {

        byte[] bytes1 = decoder.decodeBuffer(base64String);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
        BufferedImage bi1 = ImageIO.read(bais);
        return bi1;
        //ImageOutputStream w2 = new FileImageOutputStream();
        //.write(bi1, "jpg", w2);// 不管输出什么格式图片，此处不需改动

    }
    /**
     * 将图片转换成二进制
     *
     * @return
     */
    public static String getImageBinary(MultipartFile avatar) throws IOException {
        // f = new File("f://file//timg.png");
        BufferedImage bi;
        String filename = avatar.getOriginalFilename();
        bi = ImageIO.read(avatar.getInputStream());
        int i=filename.length()-1;while(i>=0&&filename.charAt(i)!='.')i--;
        //System.out.println(filename.substring(i+1,filename.length()));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, i>=0 ? filename.substring(i+1,filename.length()):"jpg", baos);  //经测试转换的图片是格式这里就什么格式，否则会失真
        byte[] bytes = baos.toByteArray();
        String str = encoder.encodeBuffer(bytes).trim();
        //将二进制转换成图片
        return str;

    }



}
